﻿using MediumApi;
using MediumApi.Db;
using MediumApi.Result;
using MediumApi.Service;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;

[ApiController]
[Route("[controller]")]
public class ChatController : BaseController
{
    private readonly ConsoleService _consoleService;
    public ChatController(ConsoleService consoleService)
    {
        _consoleService = consoleService;
    }
    /// <summary>
    /// 进入聊天室
    /// </summary>
    /// <returns></returns>
    [HttpGet("joinroom")]
    public async Task<OperateResult> JoinRoom()
    {
        try
        {
            string roomId = "9a09e3a60a494f6ebd365c461034562d";
            if (await _consoleService.AddChatRoom(roomId) > 0)
            {
                Startup.ChatRooms.TryAdd(roomId, new ChatRoomTools(roomId));
                if (HttpContext.WebSockets.IsWebSocketRequest)
                {
                    if (Startup.ChatRooms.TryGetValue(roomId, out ChatRoomTools room))
                    {
                        using (WebSocket webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync())
                        {
                            await room.AddClient(webSocket, roomId);

                            // 保持连接打开
                            while (webSocket.State == WebSocketState.Open)
                            {
                                await Task.Delay(1000);
                            }
                        }
                    }
                    else
                    {
                        HttpContext.Response.StatusCode = 404;
                    }
                }
                else
                {
                    HttpContext.Response.StatusCode = 400;
                }
            }
            return Success();
        }
        catch (Exception ex) 
        {
            return Error(ex.Message);
        }
    }
    /// <summary>
    /// 创建聊天室
    /// </summary>
    /// <returns></returns>
    [HttpPost("create")]
    public IActionResult CreateRoom()
    {
        string roomId = Guid.NewGuid().ToString();
        Startup.ChatRooms.TryAdd(roomId, new ChatRoomTools(roomId));
        return Ok(new { RoomId = roomId });
    }
    /// <summary>
    /// 进入聊天室
    /// </summary>
    /// <param name="roomId"></param>
    /// <param name="username"></param>
    /// <returns></returns>
    [HttpGet("join/{roomId}/{username}")]
    public async Task JoinRoomText(string roomId, string username)
    {
        if (HttpContext.WebSockets.IsWebSocketRequest)
        {
            if (Startup.ChatRooms.TryGetValue(roomId, out ChatRoomTools room))
            {
                using (WebSocket webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync())
                {
                    await room.AddClient(webSocket, username);

                    // 保持连接打开
                    while (webSocket.State == WebSocketState.Open)
                    {
                        await Task.Delay(1000);
                    }
                }
            }
            else
            {
                HttpContext.Response.StatusCode = 404;
            }
        }
        else
        {
            HttpContext.Response.StatusCode = 400;
        }
    }
    /// <summary>
    /// 聊天室列表
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    public async Task<OperateResult> SelectChatRoomList() 
    {
        return Success(new { ChatRoomList=  await _consoleService.SelectChatRoomList() });
    }
}